<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><div id="myscoll"></div><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>第十六-MySQL变量、流程控制与游标 | XiaoFei🥝</title><meta name="keywords" content="第十六-MySQL变量、流程控制与游标"><meta name="author" content="XiaoFei🥝"><meta name="copyright" content="XiaoFei🥝"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="第十六-MySQL变量、流程控制与游标">
<meta property="og:type" content="article">
<meta property="og:title" content="第十六-MySQL变量、流程控制与游标">
<meta property="og:url" content="https://www.naste.top:1024/posts/1122726858.html">
<meta property="og:site_name" content="XiaoFei🥝">
<meta property="og:description" content="第十六-MySQL变量、流程控制与游标">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.naste.top:9000/webp/1671882683.webp">
<meta property="article:published_time" content="2022-09-19T11:26:49.000Z">
<meta property="article:modified_time" content="2024-04-26T09:52:18.907Z">
<meta property="article:author" content="XiaoFei🥝">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.naste.top:9000/webp/1671882683.webp"><link rel="shortcut icon" href="/"><link rel="canonical" href="https://www.naste.top:1024/posts/1122726858"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.json","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.js',
      css: 'https://cdnjs.cloudflare.com/ajax/libs/flickr-justified-gallery/2.1.2/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '第十六-MySQL变量、流程控制与游标',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-04-26 17:52:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><style id="themeColor"></style><style id="rightSide"></style><style id="transPercent"></style><style id="blurNum"></style><style id="settingStyle"></style><span id="fps"></span><style id="defineBg"></style><style id="menu_shadow"></style><svg aria-hidden="true" style="position:absolute; overflow:hidden; width:0; height:0"><symbol id="icon-sun" viewBox="0 0 1024 1024"><path d="M960 512l-128 128v192h-192l-128 128-128-128H192v-192l-128-128 128-128V192h192l128-128 128 128h192v192z" fill="#FFD878" p-id="8420"></path><path d="M736 512a224 224 0 1 0-448 0 224 224 0 1 0 448 0z" fill="#FFE4A9" p-id="8421"></path><path d="M512 109.248L626.752 224H800v173.248L914.752 512 800 626.752V800h-173.248L512 914.752 397.248 800H224v-173.248L109.248 512 224 397.248V224h173.248L512 109.248M512 64l-128 128H192v192l-128 128 128 128v192h192l128 128 128-128h192v-192l128-128-128-128V192h-192l-128-128z" fill="#4D5152" p-id="8422"></path><path d="M512 320c105.888 0 192 86.112 192 192s-86.112 192-192 192-192-86.112-192-192 86.112-192 192-192m0-32a224 224 0 1 0 0 448 224 224 0 0 0 0-448z" fill="#4D5152" p-id="8423"></path></symbol><symbol id="icon-moon" viewBox="0 0 1024 1024"><path d="M611.370667 167.082667a445.013333 445.013333 0 0 1-38.4 161.834666 477.824 477.824 0 0 1-244.736 244.394667 445.141333 445.141333 0 0 1-161.109334 38.058667 85.077333 85.077333 0 0 0-65.066666 135.722666A462.08 462.08 0 1 0 747.093333 102.058667a85.077333 85.077333 0 0 0-135.722666 65.024z" fill="#FFB531" p-id="11345"></path><path d="M329.728 274.133333l35.157333-35.157333a21.333333 21.333333 0 1 0-30.165333-30.165333l-35.157333 35.157333-35.114667-35.157333a21.333333 21.333333 0 0 0-30.165333 30.165333l35.114666 35.157333-35.114666 35.157334a21.333333 21.333333 0 1 0 30.165333 30.165333l35.114667-35.157333 35.157333 35.157333a21.333333 21.333333 0 1 0 30.165333-30.165333z" fill="#030835" p-id="11346"></path></symbol></svg><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"><link rel="alternate" href="/atom.xml" title="XiaoFei🥝" type="application/atom+xml">
</head><body><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><div class="loading-img"></div><div class="loading-image-dot"></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" onerror="onerror=null;src='/assets/r1.jpg'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">149</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">99</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">46</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">XiaoFei🥝</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-home"></use></svg><span class="menu_word" style="font-size:17px"> 首页</span></a></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--article"></use></svg><span class="menu_word" style="font-size:17px"> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-guidang1">                   </use></svg><span class="menu_word" style="font-size:17px"> 归档</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-sekuaibiaoqian">                   </use></svg><span class="menu_word" style="font-size:17px"> 标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-fenlei">                   </use></svg><span class="menu_word" style="font-size:17px"> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pinweishenghuo"></use></svg><span class="menu_word" style="font-size:17px"> 休闲</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/life/music/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-yinle">                   </use></svg><span class="menu_word" style="font-size:17px"> 八音盒</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/movies/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-dianying1">                   </use></svg><span class="menu_word" style="font-size:17px"> 影院</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/life/games/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-youxishoubing">                   </use></svg><span class="menu_word" style="font-size:17px"> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xiangzi"></use></svg><span class="menu_word" style="font-size:17px"> 八宝箱</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/box/gallery/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-tubiaozhizuomoban">                   </use></svg><span class="menu_word" style="font-size:17px"> 画廊</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/animation/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-nvwumao">                   </use></svg><span class="menu_word" style="font-size:17px"> 动画</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/box/nav/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-zhifengche">                   </use></svg><span class="menu_word" style="font-size:17px"> 网址导航</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shejiaoxinxi"></use></svg><span class="menu_word" style="font-size:17px"> 社交</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/social/fcircle/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-pengyouquan">                   </use></svg><span class="menu_word" style="font-size:17px"> 朋友圈</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/comments/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-liuyan">                   </use></svg><span class="menu_word" style="font-size:17px"> 留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/social/link/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-lianjie">                   </use></svg><span class="menu_word" style="font-size:17px"> 友人帐</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-wangye"></use></svg><span class="menu_word" style="font-size:17px"> 网站</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/site/census/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon--tongjibiao">                   </use></svg><span class="menu_word" style="font-size:17px"> 网站统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/echarts/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-shujutongji1">                   </use></svg><span class="menu_word" style="font-size:17px"> 文章统计</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/site/time/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-xianxingshalou">                   </use></svg><span class="menu_word" style="font-size:17px"> 旧时光</span></a></li></ul></div><div class="menus_item"><a class="site-page group faa-parent animated-hover hide" href="javascript:void(0);"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-maoliang"></use></svg><span class="menu_word" style="font-size:17px"> 个人</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/personal/bb/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-qunliaotian">                   </use></svg><span class="menu_word" style="font-size:17px"> 唠叨</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/love/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-love-sign">                   </use></svg><span class="menu_word" style="font-size:17px"> 恋爱小屋</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/personal/about/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 关于</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/encryption/%E6%9C%BA%E5%9C%BA/"><svg class="menu_icon faa-tada" aria-hidden="true" style="width:1.30em;height:1.30em;vertical-align:-0.15em;fill:currentColor;overflow:hidden;"><use xlink:href="#icon-paperplane">                   </use></svg><span class="menu_word" style="font-size:17px"> 机场</span></a></li></ul></div></div><center id="name-container"><a id="page-name" href="javascript:scrollToTop()">PAGE_NAME</a></center><div id="nav-right"><div id="search-button"><a class="search faa-parent animated-hover" title="检索站内任何你想要的信息"><svg class="faa-tada icon" style="height:24px;width:24px;fill:currentColor;position:relative;top:6px" aria-hidden="true"><use xlink:href="#icon-valentine_-search-love-find-heart"></use></svg><span> 搜索</span></a></div><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon">       </use></svg></a><div id="toggle-menu"><a><i class="fas fa-bars fa-fw"></i></a></div></div></div></nav><div id="post-info"><h1 class="post-title">第十六-MySQL变量、流程控制与游标</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><svg class="meta_icon post-meta-icon" style="width:30px;height:30px;position:relative;top:10px"><use xlink:href="#icon-rili"></use></svg><span class="post-meta-label">发表于 </span><time class="post-meta-date-created" datetime="2022-09-19T11:26:49.000Z" title="发表于 2022-09-19 19:26:49">2022-09-19</time><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-gengxin1"></use></svg><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-04-26T09:52:18.907Z" title="更新于 2024-04-26 17:52:18">2024-04-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a><i class="fas fa-angle-right post-meta-separator"></i><svg class="meta_icon post-meta-icon" style="width:18px;height:18px;position:relative;top:5px"><use xlink:href="#icon-biaoqian"></use></svg><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/MySQL/">MySQL</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:8px"><use xlink:href="#icon-charuword"></use></svg><span class="post-meta-label">字数总计:</span><span class="word-count">8017</span><span class="post-meta-separator">|</span><svg class="meta_icon post-meta-icon" style="width:20px;height:20px;position:relative;top:5px"><use xlink:href="#icon-shizhong"></use></svg><span class="post-meta-label">阅读时长:</span><span>30分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="第十六-MySQL变量、流程控制与游标"><svg class="meta_icon post-meta-icon" style="width:25px;height:25px;position:relative;top:5px"><use xlink:href="#icon-eye"></use></svg><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第16章-变量、流程控制与游标"><a href="#第16章-变量、流程控制与游标" class="headerlink" title="第16章_变量、流程控制与游标"></a>第16章_变量、流程控制与游标</h1><h2 id="1-变量"><a href="#1-变量" class="headerlink" title="1. 变量"></a>1. 变量</h2><p>在MySQL数据库的存储过程和函数中，可以使用变量来存储查询或计算的中间结果数据，或者输出最终的结果数据。</p>
<p>在 MySQL 数据库中，变量分为<code>系统变量</code>以及<code>用户自定义变量</code>。</p>
<h3 id="1-1-系统变量"><a href="#1-1-系统变量" class="headerlink" title="1.1 系统变量"></a>1.1 系统变量</h3><h4 id="1-1-1-系统变量分类"><a href="#1-1-1-系统变量分类" class="headerlink" title="1.1.1 系统变量分类"></a>1.1.1 系统变量分类</h4><p>变量由系统定义，不是用户定义，属于<code>服务器</code>层面。启动MySQL服务，生成MySQL服务实例期间，MySQL将为MySQL服务器内存中的系统变量赋值，这些系统变量定义了当前MySQL服务实例的属性、特征。这些系统变量的值要么是<code>编译MySQL时参数</code>的默认值，要么是<code>配置文件</code>（例如my.ini等）中的参数值。大家可以通过网址 <code>https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html</code> 查看MySQL文档的系统变量。</p>
<p>系统变量分为全局系统变量（需要添加<code>global</code> 关键字）以及会话系统变量（需要添加 <code>session</code> 关键字），有时也把全局系统变量简称为全局变量，有时也把会话系统变量称为local变量。<strong>如果不写，默认会话级别。</strong>静态变量（在 MySQL 服务实例运行期间它们的值不能使用 set 动态修改）属于特殊的全局系统变量。</p>
<p>每一个MySQL客户机成功连接MySQL服务器后，都会产生与之对应的会话。会话期间，MySQL服务实例会在MySQL服务器内存中生成与该会话对应的会话系统变量，这些会话系统变量的初始值是全局系统变量值的复制。如下图：</p>
<p><img src= "" data-lazy-src="https://www.naste.top:9000/webp/image-20211108114846634.webp" alt="image-20211108114846634"></p>
<ul>
<li>全局系统变量针对于所有会话（连接）有效，但<code>不能跨重启</code></li>
<li>会话系统变量仅针对于当前会话（连接）有效。会话期间，当前会话对某个会话系统变量值的修改，不会影响其他会话同一个会话系统变量的值。</li>
<li>会话1对某个全局系统变量值的修改会导致会话2中同一个全局系统变量值的修改。</li>
</ul>
<p>在MySQL中有些系统变量只能是全局的，例如 max_connections 用于限制服务器的最大连接数；有些系统变量作用域既可以是全局又可以是会话，例如 character_set_client 用于设置客户端的字符集；有些系统变量的作用域只能是当前会话，例如 pseudo_thread_id 用于标记当前会话的 MySQL 连接 ID。</p>
<h4 id="1-1-2-查看系统变量"><a href="#1-1-2-查看系统变量" class="headerlink" title="1.1.2 查看系统变量"></a>1.1.2 查看系统变量</h4><ul>
<li><strong>查看所有或部分系统变量</strong></li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#查看所有全局变量</span><br><span class="line">SHOW GLOBAL VARIABLES;</span><br><span class="line"></span><br><span class="line">#查看所有会话变量</span><br><span class="line">SHOW SESSION VARIABLES;</span><br><span class="line">或</span><br><span class="line">SHOW VARIABLES;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#查看满足条件的部分系统变量。</span><br><span class="line">SHOW GLOBAL VARIABLES LIKE &#x27;%标识符%&#x27;;</span><br><span class="line"></span><br><span class="line">#查看满足条件的部分会话变量</span><br><span class="line">SHOW SESSION VARIABLES LIKE &#x27;%标识符%&#x27;;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SHOW GLOBAL VARIABLES LIKE &#x27;admin_%&#x27;;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>查看指定系统变量</strong></li>
</ul>
<p>作为 MySQL 编码规范，MySQL 中的系统变量以<code>两个“@”</code>开头，其中“@@global”仅用于标记全局系统变量，“@@session”仅用于标记会话系统变量。“@@”首先标记会话系统变量，如果会话系统变量不存在，则标记全局系统变量。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#查看指定的系统变量的值</span><br><span class="line">SELECT @@global.变量名;</span><br><span class="line"></span><br><span class="line">#查看指定的会话变量的值</span><br><span class="line">SELECT @@session.变量名;</span><br><span class="line">#或者</span><br><span class="line">SELECT @@变量名;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>修改系统变量的值</strong></li>
</ul>
<p>有些时候，数据库管理员需要修改系统变量的默认值，以便修改当前会话或者MySQL服务实例的属性、特征。具体方法：</p>
<p>方式1：修改MySQL<code>配置文件</code>，继而修改MySQL系统变量的值（该方法需要重启MySQL服务）</p>
<p>方式2：在MySQL服务运行期间，使用“set”命令重新设置系统变量的值</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#为某个系统变量赋值</span><br><span class="line">#方式1：</span><br><span class="line">SET @@global.变量名=变量值;</span><br><span class="line">#方式2：</span><br><span class="line">SET GLOBAL 变量名=变量值;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#为某个会话变量赋值</span><br><span class="line">#方式1：</span><br><span class="line">SET @@session.变量名=变量值;</span><br><span class="line">#方式2：</span><br><span class="line">SET SESSION 变量名=变量值;</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT @@global.autocommit;</span><br><span class="line">SET GLOBAL autocommit=0;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT @@session.tx_isolation;</span><br><span class="line">SET @@session.tx_isolation=&#x27;read-uncommitted&#x27;;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SET GLOBAL max_connections = 1000;</span><br><span class="line">SELECT @@global.max_connections;</span><br></pre></td></tr></table></figure>
<h3 id="1-2-用户变量"><a href="#1-2-用户变量" class="headerlink" title="1.2 用户变量"></a>1.2 用户变量</h3><h4 id="1-2-1-用户变量分类"><a href="#1-2-1-用户变量分类" class="headerlink" title="1.2.1 用户变量分类"></a>1.2.1 用户变量分类</h4><p>用户变量是用户自己定义的，作为 MySQL 编码规范，MySQL 中的用户变量以<code>一个“@”</code>开头。根据作用范围不同，又分为<code>会话用户变量</code>和<code>局部变量</code>。</p>
<ul>
<li><p>会话用户变量：作用域和会话变量一样，只对<code>当前连接</code>会话有效。</p>
</li>
<li><p>局部变量：只在 BEGIN 和 END 语句块中有效。局部变量只能在<code>存储过程和函数</code>中使用。</p>
</li>
</ul>
<h4 id="1-2-2-会话用户变量"><a href="#1-2-2-会话用户变量" class="headerlink" title="1.2.2 会话用户变量"></a>1.2.2 会话用户变量</h4><ul>
<li>变量的定义</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#方式1：“=”或“:=”</span><br><span class="line">SET @用户变量 = 值;</span><br><span class="line">SET @用户变量 := 值;</span><br><span class="line"></span><br><span class="line">#方式2：“:=” 或 INTO关键字</span><br><span class="line">SELECT @用户变量 := 表达式 [FROM 等子句];</span><br><span class="line">SELECT 表达式 INTO @用户变量  [FROM 等子句];</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<ul>
<li>查看用户变量的值 （查看、比较、运算等）</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT @用户变量</span><br></pre></td></tr></table></figure>
<ul>
<li>举例</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SET @a = 1;</span><br><span class="line"></span><br><span class="line">SELECT @a;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT @num := COUNT(*) FROM employees;</span><br><span class="line"></span><br><span class="line">SELECT @num;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">SELECT AVG(salary) INTO @avgsalary FROM employees;</span><br><span class="line"></span><br><span class="line">SELECT @avgsalary;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT @big;  #查看某个未声明的变量时，将得到NULL值</span><br></pre></td></tr></table></figure>
<h4 id="1-2-3-局部变量"><a href="#1-2-3-局部变量" class="headerlink" title="1.2.3 局部变量"></a>1.2.3 局部变量</h4><p>定义：可以使用<code>DECLARE</code>语句定义一个局部变量</p>
<p>作用域：仅仅在定义它的 BEGIN … END 中有效</p>
<p>位置：只能放在 BEGIN … END 中，而且只能放在第一句</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">BEGIN</span><br><span class="line">	#声明局部变量</span><br><span class="line">	DECLARE 变量名1 变量数据类型 [DEFAULT 变量默认值];</span><br><span class="line">	DECLARE 变量名2,变量名3,... 变量数据类型 [DEFAULT 变量默认值];</span><br><span class="line"></span><br><span class="line">	#为局部变量赋值</span><br><span class="line">	SET 变量名1 = 值;</span><br><span class="line">	SELECT 值 INTO 变量名2 [FROM 子句];</span><br><span class="line"></span><br><span class="line">	#查看局部变量的值</span><br><span class="line">	SELECT 变量1,变量2,变量3;</span><br><span class="line">END</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>1.定义变量</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE 变量名 类型 [default 值];  # 如果没有DEFAULT子句，初始值为NULL</span><br></pre></td></tr></table></figure>
<p>举例：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE　myparam　INT　DEFAULT 100;</span><br></pre></td></tr></table></figure>
<p><strong>2.变量赋值</strong></p>
<p>方式1：一般用于赋简单的值</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SET 变量名=值;</span><br><span class="line">SET 变量名:=值;</span><br></pre></td></tr></table></figure>
<p>方式2：一般用于赋表中的字段值</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT 字段名或表达式 INTO 变量名 FROM 表;</span><br></pre></td></tr></table></figure>
<p><strong>3.使用变量</strong>（查看、比较、运算等）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SELECT 局部变量名;</span><br></pre></td></tr></table></figure>
<p>举例1：声明局部变量，并分别赋值为employees表中employee_id为102的last_name和salary</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE set_value()</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_name VARCHAR(25);</span><br><span class="line">	DECLARE sal DOUBLE(10,2);</span><br><span class="line">	</span><br><span class="line">	SELECT last_name,salary INTO emp_name,sal</span><br><span class="line">	FROM employees </span><br><span class="line">	WHERE employee_id = 102;</span><br><span class="line">	</span><br><span class="line">	SELECT emp_name,sal;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p>举例2：声明两个变量，求和并打印 （分别使用会话用户变量、局部变量的方式实现）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">#方式1：使用用户变量</span><br><span class="line">SET @m=1;</span><br><span class="line">SET @n=1;</span><br><span class="line">SET @sum=@m+@n;</span><br><span class="line"></span><br><span class="line">SELECT @sum;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">#方式2：使用局部变量</span><br><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE add_value()</span><br><span class="line">BEGIN</span><br><span class="line">	#局部变量</span><br><span class="line">	DECLARE m INT DEFAULT 1;</span><br><span class="line">	DECLARE n INT DEFAULT 3;</span><br><span class="line">	DECLARE SUM INT;</span><br><span class="line">	</span><br><span class="line">	SET SUM = m+n;</span><br><span class="line">	SELECT SUM;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p>举例3：创建存储过程“different_salary”查询某员工和他领导的薪资差距，并用IN参数emp_id接收员工id，用OUT参数dif_salary输出薪资差距结果。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">#声明</span><br><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE different_salary(IN emp_id INT,OUT dif_salary DOUBLE)</span><br><span class="line">BEGIN</span><br><span class="line">	#声明局部变量</span><br><span class="line">	DECLARE emp_sal,mgr_sal DOUBLE DEFAULT 0.0;</span><br><span class="line">	DECLARE mgr_id INT;</span><br><span class="line">	</span><br><span class="line">	SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;</span><br><span class="line">	SELECT manager_id INTO mgr_id FROM employees WHERE employee_id = emp_id;</span><br><span class="line">	SELECT salary INTO mgr_sal FROM employees WHERE employee_id = mgr_id;</span><br><span class="line">	SET dif_salary = mgr_sal - emp_sal;</span><br><span class="line"></span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br><span class="line"></span><br><span class="line">#调用</span><br><span class="line">SET @emp_id = 102;</span><br><span class="line">CALL different_salary(@emp_id,@diff_sal);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#查看</span><br><span class="line">SELECT @diff_sal;</span><br></pre></td></tr></table></figure>
<h4 id="1-2-4-对比会话用户变量与局部变量"><a href="#1-2-4-对比会话用户变量与局部变量" class="headerlink" title="1.2.4 对比会话用户变量与局部变量"></a>1.2.4 对比会话用户变量与局部变量</h4><figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">			  作用域					定义位置				  语法</span><br><span class="line">会话用户变量	  当前会话				   会话的任何地方				加@符号，不用指定类型</span><br><span class="line">局部变量	   定义它的<span class="keyword">BEGIN</span> <span class="keyword">END</span>中 		<span class="keyword">BEGIN</span> <span class="keyword">END</span>的第一句话		  一般不用加@,需要指定类型</span><br></pre></td></tr></table></figure>
<h2 id="2-定义条件与处理程序"><a href="#2-定义条件与处理程序" class="headerlink" title="2. 定义条件与处理程序"></a>2. 定义条件与处理程序</h2><p><code>定义条件</code>是事先定义程序执行过程中可能遇到的问题，<code>处理程序</code>定义了在遇到问题时应当采取的处理方式，并且保证存储过程或函数在遇到警告或错误时能继续执行。这样可以增强存储程序处理问题的能力，避免程序异常停止运行。</p>
<p>说明：定义条件和处理程序在存储过程、存储函数中都是支持的。</p>
<h3 id="2-1-案例分析"><a href="#2-1-案例分析" class="headerlink" title="2.1 案例分析"></a>2.1 案例分析</h3><p><strong>案例分析：</strong>创建一个名称为“UpdateDataNoCondition”的存储过程。代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE UpdateDataNoCondition()</span><br><span class="line">	BEGIN</span><br><span class="line">		SET @x = 1;</span><br><span class="line">		UPDATE employees SET email = NULL WHERE last_name = &#x27;Abel&#x27;;</span><br><span class="line">		SET @x = 2;</span><br><span class="line">		UPDATE employees SET email = &#x27;aabbel&#x27; WHERE last_name = &#x27;Abel&#x27;;</span><br><span class="line">		SET @x = 3;</span><br><span class="line">	END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p>调用存储过程：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; CALL UpdateDataNoCondition();</span><br><span class="line">ERROR 1048 (23000): Column &#x27;email&#x27; cannot be null</span><br><span class="line"></span><br><span class="line">mysql&gt; SELECT @x;</span><br><span class="line">+------+</span><br><span class="line">| @x   |</span><br><span class="line">+------+</span><br><span class="line">|   1  |</span><br><span class="line">+------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>可以看到，此时@x变量的值为1。结合创建存储过程的SQL语句代码可以得出：在存储过程中未定义条件和处理程序，且当存储过程中执行的SQL语句报错时，MySQL数据库会抛出错误，并退出当前SQL逻辑，不再向下继续执行。</p>
<h3 id="2-2-定义条件"><a href="#2-2-定义条件" class="headerlink" title="2.2 定义条件"></a>2.2 定义条件</h3><p>定义条件就是给MySQL中的错误码命名，这有助于存储的程序代码更清晰。它将一个<code>错误名字</code>和<code>指定的错误条件</code>关联起来。这个名字可以随后被用在定义处理程序的<code>DECLARE HANDLER</code>语句中。</p>
<p>定义条件使用DECLARE语句，语法格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE 错误名称 CONDITION FOR 错误码（或错误条件）</span><br></pre></td></tr></table></figure>
<p>错误码的说明：</p>
<ul>
<li><code>MySQL_error_code</code>和<code>sqlstate_value</code>都可以表示MySQL的错误。<ul>
<li>MySQL_error_code是数值类型错误代码。</li>
<li>sqlstate_value是长度为5的字符串类型错误代码。</li>
</ul>
</li>
<li>例如，在ERROR 1418 (HY000)中，1418是MySQL_error_code，’HY000’是sqlstate_value。</li>
<li>例如，在ERROR 1142（42000）中，1142是MySQL_error_code，’42000’是sqlstate_value。</li>
</ul>
<p><strong>举例1：</strong>定义“Field_Not_Be_NULL”错误名与MySQL中违反非空约束的错误类型是“ERROR 1048 (23000)”对应。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#使用MySQL_error_code</span><br><span class="line">DECLARE Field_Not_Be_NULL CONDITION FOR 1048;</span><br><span class="line"></span><br><span class="line">#使用sqlstate_value</span><br><span class="line">DECLARE Field_Not_Be_NULL CONDITION FOR SQLSTATE &#x27;23000&#x27;;</span><br></pre></td></tr></table></figure>
<p><strong>举例2：</strong>定义”ERROR 1148(42000)”错误，名称为command_not_allowed。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#使用MySQL_error_code</span><br><span class="line">DECLARE command_not_allowed CONDITION FOR 1148;</span><br><span class="line"></span><br><span class="line">#使用sqlstate_value</span><br><span class="line">DECLARE command_not_allowed CONDITION FOR SQLSTATE &#x27;42000&#x27;;</span><br></pre></td></tr></table></figure>
<h3 id="2-3-定义处理程序"><a href="#2-3-定义处理程序" class="headerlink" title="2.3 定义处理程序"></a>2.3 定义处理程序</h3><p>可以为SQL执行过程中发生的某种类型的错误定义特殊的处理程序。定义处理程序时，使用DECLARE语句的语法如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE 处理方式 HANDLER FOR 错误类型 处理语句</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>处理方式</strong>：处理方式有3个取值：CONTINUE、EXIT、UNDO。<ul>
<li><code>CONTINUE</code>：表示遇到错误不处理，继续执行。</li>
<li><code>EXIT</code>：表示遇到错误马上退出。</li>
<li><code>UNDO</code>：表示遇到错误后撤回之前的操作。MySQL中暂时不支持这样的操作。</li>
</ul>
</li>
<li><strong>错误类型</strong>（即条件）可以有如下取值：<ul>
<li><code>SQLSTATE &#39;字符串错误码&#39;</code>：表示长度为5的sqlstate_value类型的错误代码；</li>
<li><code>MySQL_error_code</code>：匹配数值类型错误代码；</li>
<li><code>错误名称</code>：表示DECLARE … CONDITION定义的错误条件名称。</li>
<li><code>SQLWARNING</code>：匹配所有以01开头的SQLSTATE错误代码；</li>
<li><code>NOT FOUND</code>：匹配所有以02开头的SQLSTATE错误代码；</li>
<li><code>SQLEXCEPTION</code>：匹配所有没有被SQLWARNING或NOT FOUND捕获的SQLSTATE错误代码；</li>
</ul>
</li>
<li><strong>处理语句</strong>：如果出现上述条件之一，则采用对应的处理方式，并执行指定的处理语句。语句可以是像“<code>SET 变量 = 值</code>”这样的简单语句，也可以是使用<code>BEGIN ... END</code>编写的复合语句。</li>
</ul>
<p>定义处理程序的几种方式，代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">#方法1：捕获sqlstate_value</span><br><span class="line">DECLARE CONTINUE HANDLER FOR SQLSTATE &#x27;42S02&#x27; SET @info = &#x27;NO_SUCH_TABLE&#x27;;</span><br><span class="line"></span><br><span class="line">#方法2：捕获mysql_error_value</span><br><span class="line">DECLARE CONTINUE HANDLER FOR 1146 SET @info = &#x27;NO_SUCH_TABLE&#x27;;</span><br><span class="line"></span><br><span class="line">#方法3：先定义条件，再调用</span><br><span class="line">DECLARE no_such_table CONDITION FOR 1146;</span><br><span class="line">DECLARE CONTINUE HANDLER FOR NO_SUCH_TABLE SET @info = &#x27;NO_SUCH_TABLE&#x27;;</span><br><span class="line"></span><br><span class="line">#方法4：使用SQLWARNING</span><br><span class="line">DECLARE EXIT HANDLER FOR SQLWARNING SET @info = &#x27;ERROR&#x27;;</span><br><span class="line"></span><br><span class="line">#方法5：使用NOT FOUND</span><br><span class="line">DECLARE EXIT HANDLER FOR NOT FOUND SET @info = &#x27;NO_SUCH_TABLE&#x27;;</span><br><span class="line"></span><br><span class="line">#方法6：使用SQLEXCEPTION</span><br><span class="line">DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @info = &#x27;ERROR&#x27;;</span><br></pre></td></tr></table></figure>
<h3 id="2-4-案例解决"><a href="#2-4-案例解决" class="headerlink" title="2.4 案例解决"></a>2.4 案例解决</h3><p>在存储过程中，定义处理程序，捕获sqlstate_value值，当遇到MySQL_error_code值为1048时，执行CONTINUE操作，并且将@proc_value的值设置为-1。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE UpdateDataNoCondition()</span><br><span class="line">	BEGIN</span><br><span class="line">		#定义处理程序</span><br><span class="line">		DECLARE CONTINUE HANDLER FOR 1048 SET @proc_value = -1;</span><br><span class="line">		</span><br><span class="line">		SET @x = 1;</span><br><span class="line">		UPDATE employees SET email = NULL WHERE last_name = &#x27;Abel&#x27;;</span><br><span class="line">		SET @x = 2;</span><br><span class="line">		UPDATE employees SET email = &#x27;aabbel&#x27; WHERE last_name = &#x27;Abel&#x27;;</span><br><span class="line">		SET @x = 3;</span><br><span class="line">	END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p>调用过程：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; CALL UpdateDataWithCondition();</span><br><span class="line">Query OK, 0 rows affected (0.01 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; SELECT @x,@proc_value;</span><br><span class="line">+------+-------------+</span><br><span class="line">| @x   | @proc_value |</span><br><span class="line">+------+-------------+</span><br><span class="line">|    3 |       	 -1  |</span><br><span class="line">+------+-------------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><strong>举例：</strong></p>
<p>创建一个名称为“InsertDataWithCondition”的存储过程，代码如下。</p>
<p>在存储过程中，定义处理程序，捕获sqlstate_value值，当遇到sqlstate_value值为23000时，执行EXIT操作，并且将@proc_value的值设置为-1。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#准备工作</span><br><span class="line">CREATE TABLE departments</span><br><span class="line">AS</span><br><span class="line">SELECT * FROM atguigudb.`departments`;</span><br><span class="line"></span><br><span class="line">ALTER TABLE departments</span><br><span class="line">ADD CONSTRAINT uk_dept_name UNIQUE(department_id);</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE InsertDataWithCondition()</span><br><span class="line">	BEGIN</span><br><span class="line">		DECLARE duplicate_entry CONDITION FOR SQLSTATE &#x27;23000&#x27; ;</span><br><span class="line">		DECLARE EXIT HANDLER FOR duplicate_entry SET @proc_value = -1;</span><br><span class="line">		</span><br><span class="line">		SET @x = 1;</span><br><span class="line">		INSERT INTO departments(department_name) VALUES(&#x27;测试&#x27;);</span><br><span class="line">		SET @x = 2;</span><br><span class="line">		INSERT INTO departments(department_name) VALUES(&#x27;测试&#x27;);</span><br><span class="line">		SET @x = 3;</span><br><span class="line">	END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p>调用存储过程：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; CALL InsertDataWithCondition();</span><br><span class="line">Query OK, 0 rows affected (0.01 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; SELECT @x,@proc_value;</span><br><span class="line">+------+-------------+</span><br><span class="line">| @x   | @proc_value |</span><br><span class="line">+------+-------------+</span><br><span class="line">|    2 |       	 -1  |</span><br><span class="line">+------+-------------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="3-流程控制"><a href="#3-流程控制" class="headerlink" title="3. 流程控制"></a>3. 流程控制</h2><p>解决复杂问题不可能通过一个 SQL 语句完成，我们需要执行多个 SQL 操作。流程控制语句的作用就是控制存储过程中 SQL 语句的执行顺序，是我们完成复杂操作必不可少的一部分。只要是执行的程序，流程就分为三大类：</p>
<ul>
<li><code>顺序结构</code>：程序从上往下依次执行</li>
<li><code>分支结构</code>：程序按条件进行选择执行，从两条或多条路径中选择一条执行</li>
<li><code>循环结构</code>：程序满足一定条件下，重复执行一组语句</li>
</ul>
<p>针对于MySQL 的流程控制语句主要有 3 类。注意：只能用于存储程序。</p>
<ul>
<li><code>条件判断语句</code>：IF 语句和 CASE 语句</li>
<li><code>循环语句</code>：LOOP、WHILE 和 REPEAT 语句</li>
<li><code>跳转语句</code>：ITERATE 和 LEAVE 语句</li>
</ul>
<h3 id="3-1-分支结构之-IF"><a href="#3-1-分支结构之-IF" class="headerlink" title="3.1 分支结构之 IF"></a>3.1 分支结构之 IF</h3><ul>
<li>IF 语句的语法结构是：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">IF 表达式1 THEN 操作1</span><br><span class="line">[ELSEIF 表达式2 THEN 操作2]……</span><br><span class="line">[ELSE 操作N]</span><br><span class="line">END IF</span><br></pre></td></tr></table></figure>
<p>根据表达式的结果为TRUE或FALSE执行相应的语句。这里“[]”中的内容是可选的。</p>
<ul>
<li><p>特点：① 不同的表达式对应不同的操作 ② 使用在begin end中</p>
</li>
<li><p><strong>举例1：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">IF val IS NULL </span><br><span class="line">	THEN SELECT &#x27;val is null&#x27;;</span><br><span class="line">ELSE SELECT &#x27;val is not null&#x27;;</span><br><span class="line"></span><br><span class="line">END IF;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>举例2：</strong>声明存储过程“update_salary_by_eid1”，定义IN参数emp_id，输入员工编号。判断该员工薪资如果低于8000元并且入职时间超过5年，就涨薪500元；否则就不变。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_by_eid1(IN emp_id INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_salary DOUBLE;</span><br><span class="line">	DECLARE hire_year DOUBLE;</span><br><span class="line"></span><br><span class="line">	SELECT salary INTO emp_salary FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	SELECT DATEDIFF(CURDATE(),hire_date)/365 INTO hire_year</span><br><span class="line">	FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	IF emp_salary &lt; 8000 AND hire_year &gt; 5</span><br><span class="line">	THEN UPDATE employees SET salary = salary + 500 WHERE employee_id = emp_id;</span><br><span class="line">	END IF;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>举例3：</strong>声明存储过程“update_salary_by_eid2”，定义IN参数emp_id，输入员工编号。判断该员工薪资如果低于9000元并且入职时间超过5年，就涨薪500元；否则就涨薪100元。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_by_eid2(IN emp_id INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_salary DOUBLE;</span><br><span class="line">	DECLARE hire_year DOUBLE;</span><br><span class="line"></span><br><span class="line">	SELECT salary INTO emp_salary FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	SELECT DATEDIFF(CURDATE(),hire_date)/365 INTO hire_year</span><br><span class="line">	FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	IF emp_salary &lt; 8000 AND hire_year &gt; 5</span><br><span class="line">		THEN UPDATE employees SET salary = salary + 500 WHERE employee_id = emp_id;</span><br><span class="line">	ELSE </span><br><span class="line">		UPDATE employees SET salary = salary + 100 WHERE employee_id = emp_id;</span><br><span class="line">	END IF;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>举例4：</strong>声明存储过程“update_salary_by_eid3”，定义IN参数emp_id，输入员工编号。判断该员工薪资如果低于9000元，就更新薪资为9000元；薪资如果大于等于9000元且低于10000的，但是奖金比例为NULL的，就更新奖金比例为0.01；其他的涨薪100元。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_by_eid3(IN emp_id INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_salary DOUBLE;</span><br><span class="line">	DECLARE bonus DECIMAL(3,2);</span><br><span class="line"></span><br><span class="line">	SELECT salary INTO emp_salary FROM employees WHERE employee_id = emp_id;</span><br><span class="line">	SELECT commission_pct INTO bonus FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	IF emp_salary &lt; 9000</span><br><span class="line">		THEN UPDATE employees SET salary = 9000 WHERE employee_id = emp_id;</span><br><span class="line">	ELSEIF emp_salary &lt; 10000 AND bonus IS NULL</span><br><span class="line">		THEN UPDATE employees SET commission_pct = 0.01 WHERE employee_id = emp_id;</span><br><span class="line">	ELSE</span><br><span class="line">		UPDATE employees SET salary = salary + 100 WHERE employee_id = emp_id;</span><br><span class="line">	END IF;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="3-2-分支结构之-CASE"><a href="#3-2-分支结构之-CASE" class="headerlink" title="3.2 分支结构之 CASE"></a>3.2 分支结构之 CASE</h3><p>CASE 语句的语法结构1：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#情况一：类似于switch</span><br><span class="line">CASE 表达式</span><br><span class="line">WHEN 值1 THEN 结果1或语句1(如果是语句，需要加分号) </span><br><span class="line">WHEN 值2 THEN 结果2或语句2(如果是语句，需要加分号)</span><br><span class="line">...</span><br><span class="line">ELSE 结果n或语句n(如果是语句，需要加分号)</span><br><span class="line">END [case]（如果是放在begin end中需要加上case，如果放在select后面不需要）</span><br></pre></td></tr></table></figure>
<p>CASE 语句的语法结构2：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#情况二：类似于多重if</span><br><span class="line">CASE </span><br><span class="line">WHEN 条件1 THEN 结果1或语句1(如果是语句，需要加分号) </span><br><span class="line">WHEN 条件2 THEN 结果2或语句2(如果是语句，需要加分号)</span><br><span class="line">...</span><br><span class="line">ELSE 结果n或语句n(如果是语句，需要加分号)</span><br><span class="line">END [case]（如果是放在begin end中需要加上case，如果放在select后面不需要）</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>举例1：</strong></li>
</ul>
<p>使用CASE流程控制语句的第1种格式，判断val值等于1、等于2，或者两者都不等。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CASE val</span><br><span class="line">　　　WHEN 1 THEN SELECT &#x27;val is 1&#x27;;</span><br><span class="line">　　　WHEN 2 THEN SELECT &#x27;val is 2&#x27;;</span><br><span class="line">　　　ELSE SELECT &#x27;val is not 1 or 2&#x27;;</span><br><span class="line">END CASE;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>举例2：</strong></li>
</ul>
<p>使用CASE流程控制语句的第2种格式，判断val是否为空、小于0、大于0或者等于0。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">CASE</span><br><span class="line">	WHEN val IS NULL THEN SELECT &#x27;val is null&#x27;;</span><br><span class="line">	WHEN val &lt; 0 THEN SELECT &#x27;val is less than 0&#x27;;</span><br><span class="line">	WHEN val &gt; 0 THEN SELECT &#x27;val is greater than 0&#x27;;</span><br><span class="line">	ELSE SELECT &#x27;val is 0&#x27;;</span><br><span class="line">END CASE;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>举例3：</strong>声明存储过程“update_salary_by_eid4”，定义IN参数emp_id，输入员工编号。判断该员工薪资如果低于9000元，就更新薪资为9000元；薪资大于等于9000元且低于10000的，但是奖金比例为NULL的，就更新奖金比例为0.01；其他的涨薪100元。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_by_eid4(IN emp_id INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_sal DOUBLE;</span><br><span class="line">	DECLARE bonus DECIMAL(3,2);</span><br><span class="line"></span><br><span class="line">	SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;</span><br><span class="line">	SELECT commission_pct INTO bonus FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	CASE</span><br><span class="line">	WHEN emp_sal&lt;9000</span><br><span class="line">		THEN UPDATE employees SET salary=9000 WHERE employee_id = emp_id;</span><br><span class="line">	WHEN emp_sal&lt;10000 AND bonus IS NULL</span><br><span class="line">		THEN UPDATE employees SET commission_pct=0.01 WHERE employee_id = emp_id;</span><br><span class="line">	ELSE</span><br><span class="line">		UPDATE employees SET salary=salary+100 WHERE employee_id = emp_id;</span><br><span class="line">	END CASE;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<ul>
<li>举例4：声明存储过程update_salary_by_eid5，定义IN参数emp_id，输入员工编号。判断该员工的入职年限，如果是0年，薪资涨50；如果是1年，薪资涨100；如果是2年，薪资涨200；如果是3年，薪资涨300；如果是4年，薪资涨400；其他的涨薪500。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_by_eid5(IN emp_id INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE emp_sal DOUBLE;</span><br><span class="line">	DECLARE hire_year DOUBLE;</span><br><span class="line"></span><br><span class="line">	SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;</span><br><span class="line">	</span><br><span class="line">	SELECT ROUND(DATEDIFF(CURDATE(),hire_date)/365) INTO hire_year FROM employees WHERE employee_id = emp_id;</span><br><span class="line"></span><br><span class="line">	CASE hire_year</span><br><span class="line">		WHEN 0 THEN UPDATE employees SET salary=salary+50 WHERE employee_id = emp_id;</span><br><span class="line">		WHEN 1 THEN UPDATE employees SET salary=salary+100 WHERE employee_id = emp_id;</span><br><span class="line">		WHEN 2 THEN UPDATE employees SET salary=salary+200 WHERE employee_id = emp_id;</span><br><span class="line">		WHEN 3 THEN UPDATE employees SET salary=salary+300 WHERE employee_id = emp_id;</span><br><span class="line">		WHEN 4 THEN UPDATE employees SET salary=salary+400 WHERE employee_id = emp_id;</span><br><span class="line">		ELSE UPDATE employees SET salary=salary+500 WHERE employee_id = emp_id;</span><br><span class="line">	END CASE;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h3 id="3-3-循环结构之LOOP"><a href="#3-3-循环结构之LOOP" class="headerlink" title="3.3 循环结构之LOOP"></a>3.3 循环结构之LOOP</h3><p>LOOP循环语句用来重复执行某些语句。LOOP内的语句一直重复执行直到循环被退出（使用LEAVE子句），跳出循环过程。</p>
<p>LOOP语句的基本格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[loop_label:] LOOP</span><br><span class="line">	循环执行的语句</span><br><span class="line">END LOOP [loop_label]</span><br></pre></td></tr></table></figure>
<p>其中，loop_label表示LOOP语句的标注名称，该参数可以省略。</p>
<p><strong>举例1：</strong></p>
<p>使用LOOP语句进行循环操作，id值小于10时将重复执行循环过程。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">DECLARE id INT DEFAULT 0;</span><br><span class="line">add_loop:LOOP</span><br><span class="line">	SET id = id +1;</span><br><span class="line">	IF id &gt;= 10 THEN LEAVE add_loop;</span><br><span class="line">	END IF;</span><br><span class="line"></span><br><span class="line">END LOOP add_loop;</span><br></pre></td></tr></table></figure>
<p><strong>举例2：</strong>当市场环境变好时，公司为了奖励大家，决定给大家涨工资。声明存储过程“update_salary_loop()”，声明OUT参数num，输出循环次数。存储过程中实现循环给大家涨薪，薪资涨为原来的1.1倍。直到全公司的平均薪资达到12000结束。并统计循环次数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_loop(OUT num INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE avg_salary DOUBLE;</span><br><span class="line">	DECLARE loop_count INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	SELECT AVG(salary) INTO avg_salary FROM employees;</span><br><span class="line">	</span><br><span class="line">	label_loop:LOOP</span><br><span class="line">		IF avg_salary &gt;= 12000 THEN LEAVE label_loop;</span><br><span class="line">		END IF;</span><br><span class="line">		</span><br><span class="line">		UPDATE employees SET salary = salary * 1.1;</span><br><span class="line">		SET loop_count = loop_count + 1;</span><br><span class="line">		SELECT AVG(salary) INTO avg_salary FROM employees;</span><br><span class="line">	END LOOP label_loop;</span><br><span class="line">	</span><br><span class="line">	SET num = loop_count;</span><br><span class="line"></span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h3 id="3-4-循环结构之WHILE"><a href="#3-4-循环结构之WHILE" class="headerlink" title="3.4 循环结构之WHILE"></a>3.4 循环结构之WHILE</h3><p>WHILE语句创建一个带条件判断的循环过程。WHILE在执行语句执行时，先对指定的表达式进行判断，如果为真，就执行循环内的语句，否则退出循环。WHILE语句的基本格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[while_label:] WHILE 循环条件  DO</span><br><span class="line">	循环体</span><br><span class="line">END WHILE [while_label];</span><br></pre></td></tr></table></figure>
<p>while_label为WHILE语句的标注名称；如果循环条件结果为真，WHILE语句内的语句或语句群被执行，直至循环条件为假，退出循环。</p>
<p><strong>举例1：</strong></p>
<p>WHILE语句示例，i值小于10时，将重复执行循环过程，代码如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE test_while()</span><br><span class="line">BEGIN	</span><br><span class="line">	DECLARE i INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	WHILE i &lt; 10 DO</span><br><span class="line">		SET i = i + 1;</span><br><span class="line">	END WHILE;</span><br><span class="line">	</span><br><span class="line">	SELECT i;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br><span class="line">#调用</span><br><span class="line">CALL test_while();</span><br></pre></td></tr></table></figure>
<p><strong>举例2：</strong>市场环境不好时，公司为了渡过难关，决定暂时降低大家的薪资。声明存储过程“update_salary_while()”，声明OUT参数num，输出循环次数。存储过程中实现循环给大家降薪，薪资降为原来的90%。直到全公司的平均薪资达到5000结束。并统计循环次数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_while(OUT num INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE avg_sal DOUBLE ;</span><br><span class="line">	DECLARE while_count INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	SELECT AVG(salary) INTO avg_sal FROM employees;</span><br><span class="line">	</span><br><span class="line">	WHILE avg_sal &gt; 5000 DO</span><br><span class="line">		UPDATE employees SET salary = salary * 0.9;</span><br><span class="line">		</span><br><span class="line">		SET while_count = while_count + 1;</span><br><span class="line">		</span><br><span class="line">		SELECT AVG(salary) INTO avg_sal FROM employees;</span><br><span class="line">	END WHILE;</span><br><span class="line">	</span><br><span class="line">	SET num = while_count;</span><br><span class="line"></span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h3 id="3-5-循环结构之REPEAT"><a href="#3-5-循环结构之REPEAT" class="headerlink" title="3.5 循环结构之REPEAT"></a>3.5 循环结构之REPEAT</h3><p>REPEAT语句创建一个带条件判断的循环过程。与WHILE循环不同的是，REPEAT 循环首先会执行一次循环，然后在 UNTIL 中进行表达式的判断，如果满足条件就退出，即 END REPEAT；如果条件不满足，则会就继续执行循环，直到满足退出条件为止。</p>
<p>REPEAT语句的基本格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[repeat_label:] REPEAT</span><br><span class="line">　　　　循环体的语句</span><br><span class="line">UNTIL 结束循环的条件表达式</span><br><span class="line">END REPEAT [repeat_label]</span><br></pre></td></tr></table></figure>
<p>repeat_label为REPEAT语句的标注名称，该参数可以省略；REPEAT语句内的语句或语句群被重复，直至expr_condition为真。</p>
<p><strong>举例1：</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE test_repeat()</span><br><span class="line">BEGIN	</span><br><span class="line">	DECLARE i INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	REPEAT </span><br><span class="line">		SET i = i + 1;</span><br><span class="line">	UNTIL i &gt;= 10</span><br><span class="line">	END REPEAT;</span><br><span class="line">	</span><br><span class="line">	SELECT i;</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p><strong>举例2：</strong>当市场环境变好时，公司为了奖励大家，决定给大家涨工资。声明存储过程“update_salary_repeat()”，声明OUT参数num，输出循环次数。存储过程中实现循环给大家涨薪，薪资涨为原来的1.15倍。直到全公司的平均薪资达到13000结束。并统计循环次数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE update_salary_repeat(OUT num INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE avg_sal DOUBLE ;</span><br><span class="line">	DECLARE repeat_count INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	SELECT AVG(salary) INTO avg_sal FROM employees;</span><br><span class="line">	</span><br><span class="line">	REPEAT</span><br><span class="line">		UPDATE employees SET salary = salary * 1.15;</span><br><span class="line">		</span><br><span class="line">		SET repeat_count = repeat_count + 1;</span><br><span class="line">		</span><br><span class="line">		SELECT AVG(salary) INTO avg_sal FROM employees;</span><br><span class="line">	UNTIL avg_sal &gt;= 13000</span><br><span class="line">	END REPEAT;</span><br><span class="line">	</span><br><span class="line">	SET num = repeat_count;</span><br><span class="line">		</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p><strong>对比三种循环结构：</strong></p>
<p>1、这三种循环都可以省略名称，但如果循环中添加了循环控制语句（LEAVE或ITERATE）则必须添加名称。<br>2、<br>LOOP：一般用于实现简单的”死”循环<br>WHILE：先判断后执行<br>REPEAT：先执行后判断，无条件至少执行一次</p>
<h3 id="3-6-跳转语句之LEAVE语句"><a href="#3-6-跳转语句之LEAVE语句" class="headerlink" title="3.6 跳转语句之LEAVE语句"></a>3.6 跳转语句之LEAVE语句</h3><p>LEAVE语句：可以用在循环语句内，或者以 BEGIN 和 END 包裹起来的程序体内，表示跳出循环或者跳出程序体的操作。如果你有面向过程的编程语言的使用经验，你可以把 LEAVE 理解为 break。</p>
<p>基本格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LEAVE 标记名</span><br></pre></td></tr></table></figure>
<p>其中，label参数表示循环的标志。LEAVE和BEGIN … END或循环一起被使用。</p>
<p><strong>举例1：</strong>创建存储过程 “leave_begin()”，声明INT类型的IN参数num。给BEGIN…END加标记名，并在BEGIN…END中使用IF语句判断num参数的值。</p>
<ul>
<li>如果num&lt;=0，则使用LEAVE语句退出BEGIN…END；</li>
<li>如果num=1，则查询“employees”表的平均薪资；</li>
<li>如果num=2，则查询“employees”表的最低薪资；</li>
<li>如果num&gt;2，则查询“employees”表的最高薪资。</li>
</ul>
<p>IF语句结束后查询“employees”表的总人数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE leave_begin(IN num INT)</span><br><span class="line"></span><br><span class="line">	begin_label: BEGIN</span><br><span class="line">		IF num&lt;=0 </span><br><span class="line">			THEN LEAVE begin_label;</span><br><span class="line">		ELSEIF num=1 </span><br><span class="line">			THEN SELECT AVG(salary) FROM employees;</span><br><span class="line">		ELSEIF num=2 </span><br><span class="line">			THEN SELECT MIN(salary) FROM employees;</span><br><span class="line">		ELSE </span><br><span class="line">			SELECT MAX(salary) FROM employees;</span><br><span class="line">		END IF;</span><br><span class="line">		</span><br><span class="line">		SELECT COUNT(*) FROM employees;</span><br><span class="line">	END //</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<p><strong>举例2：</strong></p>
<p>当市场环境不好时，公司为了渡过难关，决定暂时降低大家的薪资。声明存储过程“leave_while()”，声明OUT参数num，输出循环次数，存储过程中使用WHILE循环给大家降低薪资为原来薪资的90%，直到全公司的平均薪资小于等于10000，并统计循环次数。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line">CREATE PROCEDURE leave_while(OUT num INT)</span><br><span class="line"></span><br><span class="line">BEGIN </span><br><span class="line">	#</span><br><span class="line">	DECLARE avg_sal DOUBLE;#记录平均工资</span><br><span class="line">	DECLARE while_count INT DEFAULT 0; #记录循环次数</span><br><span class="line">	</span><br><span class="line">	SELECT AVG(salary) INTO avg_sal FROM employees; #① 初始化条件</span><br><span class="line">	</span><br><span class="line">	while_label:WHILE TRUE DO  #② 循环条件</span><br><span class="line">		</span><br><span class="line">		#③ 循环体</span><br><span class="line">		IF avg_sal &lt;= 10000 THEN</span><br><span class="line">			LEAVE while_label;</span><br><span class="line">		END IF;</span><br><span class="line">		</span><br><span class="line">		UPDATE employees SET salary  = salary * 0.9;</span><br><span class="line">		SET while_count = while_count + 1;</span><br><span class="line">		</span><br><span class="line">		#④ 迭代条件</span><br><span class="line">		SELECT AVG(salary) INTO avg_sal FROM employees;</span><br><span class="line">	</span><br><span class="line">	END WHILE;</span><br><span class="line">	</span><br><span class="line">	#赋值</span><br><span class="line">	SET num = while_count;</span><br><span class="line"></span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h3 id="3-7-跳转语句之ITERATE语句"><a href="#3-7-跳转语句之ITERATE语句" class="headerlink" title="3.7 跳转语句之ITERATE语句"></a>3.7 跳转语句之ITERATE语句</h3><p>ITERATE语句：只能用在循环语句（LOOP、REPEAT和WHILE语句）内，表示重新开始循环，将执行顺序转到语句段开头处。如果你有面向过程的编程语言的使用经验，你可以把 ITERATE 理解为 continue，意思为“再次循环”。</p>
<p>语句基本格式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ITERATE label</span><br></pre></td></tr></table></figure>
<p>label参数表示循环的标志。ITERATE语句必须跟在循环标志前面。</p>
<p><strong>举例：</strong>  定义局部变量num，初始值为0。循环结构中执行num + 1操作。</p>
<ul>
<li>如果num &lt; 10，则继续执行循环；</li>
<li>如果num &gt; 15，则退出循环结构；</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE test_iterate()</span><br><span class="line"></span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE num INT DEFAULT 0;</span><br><span class="line">	</span><br><span class="line">	my_loop:LOOP</span><br><span class="line">		SET num = num + 1;</span><br><span class="line">	</span><br><span class="line">		IF num &lt; 10 </span><br><span class="line">			THEN ITERATE my_loop;</span><br><span class="line">		ELSEIF num &gt; 15 </span><br><span class="line">			THEN LEAVE my_loop;</span><br><span class="line">		END IF;</span><br><span class="line">	</span><br><span class="line">		SELECT &#x27;尚硅谷：让天下没有难学的技术&#x27;;</span><br><span class="line">	</span><br><span class="line">	END LOOP my_loop;</span><br><span class="line"></span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h2 id="4-游标"><a href="#4-游标" class="headerlink" title="4. 游标"></a>4. 游标</h2><h3 id="4-1-什么是游标（或光标）"><a href="#4-1-什么是游标（或光标）" class="headerlink" title="4.1 什么是游标（或光标）"></a>4.1 什么是游标（或光标）</h3><p>虽然我们也可以通过筛选条件 WHERE 和 HAVING，或者是限定返回记录的关键字 LIMIT 返回一条记录，但是，却无法在结果集中像指针一样，向前定位一条记录、向后定位一条记录，或者是<code>随意定位到某一条记录</code>，并对记录的数据进行处理。</p>
<p>这个时候，就可以用到游标。游标，提供了一种灵活的操作方式，让我们能够对结果集中的每一条记录进行定位，并对指向的记录中的数据进行操作的数据结构。<strong>游标让 SQL 这种面向集合的语言有了面向过程开发的能力。</strong></p>
<p>在 SQL 中，游标是一种临时的数据库对象，可以指向存储在数据库表中的数据行指针。这里游标<code>充当了指针的作用</code>，我们可以通过操作游标来对数据行进行操作。</p>
<p>MySQL中游标可以在存储过程和函数中使用。</p>
<p>比如，我们查询了 employees 数据表中工资高于15000的员工都有哪些：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SELECT employee_id,last_name,salary FROM employees</span><br><span class="line">WHERE salary &gt; 15000;</span><br></pre></td></tr></table></figure>
<p> <img src= "" data-lazy-src="https://www.naste.top:9000/webp/image-20211111182656990.webp" alt="image-20211111182656990"></p>
<p>这里我们就可以通过游标来操作数据行，如图所示此时游标所在的行是“108”的记录，我们也可以在结果集上滚动游标，指向结果集中的任意一行。</p>
<h3 id="4-2-使用游标步骤"><a href="#4-2-使用游标步骤" class="headerlink" title="4.2 使用游标步骤"></a>4.2 使用游标步骤</h3><p>游标必须在声明处理程序之前被声明，并且变量和条件还必须在声明游标或处理程序之前被声明。</p>
<p>如果我们想要使用游标，一般需要经历四个步骤。不同的 DBMS 中，使用游标的语法可能略有不同。</p>
<p><strong>第一步，声明游标</strong></p>
<p>在MySQL中，使用DECLARE关键字来声明游标，其语法的基本形式如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE cursor_name CURSOR FOR select_statement; </span><br></pre></td></tr></table></figure>
<p>这个语法适用于 MySQL，SQL Server，DB2 和 MariaDB。如果是用 Oracle 或者 PostgreSQL，需要写成：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DECLARE cursor_name CURSOR IS select_statement;</span><br></pre></td></tr></table></figure>
<p>要使用 SELECT 语句来获取数据结果集，而此时还没有开始遍历数据，这里 select_statement 代表的是 SELECT 语句，返回一个用于创建游标的结果集。</p>
<p>比如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">DECLARE cur_emp CURSOR FOR </span><br><span class="line">SELECT employee_id,salary FROM employees;</span><br></pre></td></tr></table></figure>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">DECLARE cursor_fruit CURSOR FOR </span><br><span class="line">SELECT f_name, f_price FROM fruits ;</span><br></pre></td></tr></table></figure>
<p><strong>第二步，打开游标</strong></p>
<p>打开游标的语法如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">OPEN cursor_name</span><br></pre></td></tr></table></figure>
<p>当我们定义好游标之后，如果想要使用游标，必须先打开游标。打开游标的时候 SELECT 语句的查询结果集就会送到游标工作区，为后面游标的<code>逐条读取</code>结果集中的记录做准备。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">OPEN　cur_emp ;</span><br></pre></td></tr></table></figure>
<p><strong>第三步，使用游标（从游标中取得数据）</strong></p>
<p>语法如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FETCH cursor_name INTO var_name [, var_name] ...</span><br></pre></td></tr></table></figure>
<p>这句的作用是使用 cursor_name 这个游标来读取当前行，并且将数据保存到 var_name 这个变量中，游标指针指到下一行。如果游标读取的数据行有多个列名，则在 INTO 关键字后面赋值给多个变量名即可。</p>
<p>注意：var_name必须在声明游标之前就定义好。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FETCH　cur_emp INTO emp_id, emp_sal ;</span><br></pre></td></tr></table></figure>
<p>注意：<strong>游标的查询结果集中的字段数，必须跟 INTO 后面的变量数一致</strong>，否则，在存储过程执行的时候，MySQL 会提示错误。</p>
<p><strong>第四步，关闭游标</strong></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CLOSE cursor_name</span><br></pre></td></tr></table></figure>
<p>有 OPEN 就会有 CLOSE，也就是打开和关闭游标。当我们使用完游标后需要关闭掉该游标。因为游标会<code>占用系统资源</code>，如果不及时关闭，<strong>游标会一直保持到存储过程结束</strong>，影响系统运行的效率。而关闭游标的操作，会释放游标占用的系统资源。</p>
<p>关闭游标之后，我们就不能再检索查询结果中的数据行，如果需要检索只能再次打开游标。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CLOSE　cur_emp;</span><br></pre></td></tr></table></figure>
<h3 id="4-3-举例"><a href="#4-3-举例" class="headerlink" title="4.3 举例"></a>4.3 举例</h3><p>创建存储过程“get_count_by_limit_total_salary()”，声明IN参数 limit_total_salary，DOUBLE类型；声明OUT参数total_count，INT类型。函数的功能可以实现累加薪资最高的几个员工的薪资值，直到薪资总和达到limit_total_salary参数的值，返回累加的人数给total_count。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">DELIMITER //</span><br><span class="line"></span><br><span class="line">CREATE PROCEDURE get_count_by_limit_total_salary(IN limit_total_salary DOUBLE,OUT total_count INT)</span><br><span class="line"></span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE sum_salary DOUBLE DEFAULT 0;  #记录累加的总工资</span><br><span class="line">	DECLARE cursor_salary DOUBLE DEFAULT 0; #记录某一个工资值</span><br><span class="line">	DECLARE emp_count INT DEFAULT 0; #记录循环个数</span><br><span class="line">	#定义游标</span><br><span class="line">	DECLARE emp_cursor CURSOR FOR SELECT salary FROM employees ORDER BY salary DESC;</span><br><span class="line">	#打开游标</span><br><span class="line">	OPEN emp_cursor;</span><br><span class="line">	</span><br><span class="line">	REPEAT</span><br><span class="line">		#使用游标（从游标中获取数据）</span><br><span class="line">		FETCH emp_cursor INTO cursor_salary;</span><br><span class="line">		</span><br><span class="line">		SET sum_salary = sum_salary + cursor_salary;</span><br><span class="line">		SET emp_count = emp_count + 1;</span><br><span class="line">		</span><br><span class="line">		UNTIL sum_salary &gt;= limit_total_salary</span><br><span class="line">	END REPEAT;</span><br><span class="line">	</span><br><span class="line">	SET total_count = emp_count;</span><br><span class="line">	#关闭游标</span><br><span class="line">	CLOSE emp_cursor;</span><br><span class="line">	</span><br><span class="line">END //</span><br><span class="line"></span><br><span class="line">DELIMITER ;</span><br></pre></td></tr></table></figure>
<h3 id="4-5-小结"><a href="#4-5-小结" class="headerlink" title="4.5 小结"></a>4.5 小结</h3><p>游标是 MySQL 的一个重要的功能，为<code>逐条读取</code>结果集中的数据，提供了完美的解决方案。跟在应用层面实现相同的功能相比，游标可以在存储程序中使用，效率高，程序也更加简洁。</p>
<p>但同时也会带来一些性能问题，比如在使用游标的过程中，会对数据行进行<code>加锁</code>，这样在业务并发量大的时候，不仅会影响业务之间的效率，还会<code>消耗系统资源</code>，造成内存不足，这是因为游标是在内存中进行的处理。</p>
<p>建议：养成用完之后就关闭的习惯，这样才能提高系统的整体效率。</p>
<h2 id="补充：MySQL-8-0的新特性—全局变量的持久化"><a href="#补充：MySQL-8-0的新特性—全局变量的持久化" class="headerlink" title="补充：MySQL 8.0的新特性—全局变量的持久化"></a>补充：MySQL 8.0的新特性—全局变量的持久化</h2><p>在MySQL数据库中，全局变量可以通过SET GLOBAL语句来设置。例如，设置服务器语句超时的限制，可以通过设置系统变量max_execution_time来实现：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SET GLOBAL MAX_EXECUTION_TIME=2000;</span><br></pre></td></tr></table></figure>
<p>使用SET GLOBAL语句设置的变量值只会<code>临时生效</code>。<code>数据库重启</code>后，服务器又会从MySQL配置文件中读取变量的默认值。<br>MySQL 8.0版本新增了<code>SET PERSIST</code>命令。例如，设置服务器的最大连接数为1000：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SET PERSIST global max_connections = 1000;</span><br></pre></td></tr></table></figure>
<p>MySQL会将该命令的配置保存到数据目录下的<code>mysqld-auto.cnf</code>文件中，下次启动时会读取该文件，用其中的配置来覆盖默认的配置文件。</p>
<p>举例：</p>
<p>查看全局变量max_connections的值，结果如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; show variables like &#x27;%max_connections%&#x27;;</span><br><span class="line">+------------------------+-------+</span><br><span class="line">| Variable_name          | Value |</span><br><span class="line">+------------------------+-------+</span><br><span class="line">| max_connections        | 151   |</span><br><span class="line">| mysqlx_max_connections | 100   |</span><br><span class="line">+------------------------+-------+</span><br><span class="line">2 rows in set, 1 warning (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>设置全局变量max_connections的值：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; set persist max_connections=1000;</span><br><span class="line">Query OK, 0 rows affected (0.00 sec)</span><br></pre></td></tr></table></figure>
<p><code>重启MySQL服务器</code>，再次查询max_connections的值：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; show variables like &#x27;%max_connections%&#x27;;</span><br><span class="line">+------------------------+-------+</span><br><span class="line">| Variable_name          | Value |</span><br><span class="line">+------------------------+-------+</span><br><span class="line">| max_connections        | 1000  |</span><br><span class="line">| mysqlx_max_connections | 100   |</span><br><span class="line">+------------------------+-------+</span><br><span class="line">2 rows in set, 1 warning (0.00 sec)</span><br></pre></td></tr></table></figure>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>第十六-MySQL变量、流程控制与游标</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="https://www.naste.top:1024/posts/1122726858.html">https://www.naste.top:1024/posts/1122726858.html</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>XiaoFei🥝</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2022-09-19</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2024-04-26</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MySQL/"><div class="tags-punctuation"><svg class="faa-tada icon" style="height:1.1em;width:1.1em;fill:currentColor;position:relative;top:2px;margin-right:3px" aria-hidden="true"><use xlink:href="#icon-sekuaibiaoqian"></use></svg></div>MySQL</a></div></div><link rel="stylesheet" href="/css/coin.css" media="defer" onload="this.media='all'"/><div class="post-reward"><button class="tip-button reward-button"><span class="tip-button__text">投喂作者</span><div class="coin-wrapper"><div class="coin"><div class="coin__middle"></div><div class="coin__back"></div><div class="coin__front"></div></div></div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://www.naste.top:9000/images/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://www.naste.top:9000/images/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://www.naste.top:9000/images/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></button></div><audio id="coinAudio" src="https://npm.elemecdn.com/akilar-candyassets@1.0.36/audio/aowu.m4a"></audio><script defer="defer" src="/js/coin.js"></script><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/1494519188.html"><img class="prev-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1671882661.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">第十七-MySQL触发器</div></div></a></div><div class="next-post pull-right"><a href="/posts/1192994447.html"><img class="next-cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912187.webp" onerror="onerror=null;src='/assets/r2.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">第十五-MySQL存储过程和函数</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/2414116852.html" title="JDBC"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743784.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">JDBC</div></div></a></div><div><a href="/posts/3169224211.html" title="MySQL基础"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912182.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL基础</div></div></a></div><div><a href="/posts/316116237.html" title="MySQL数据库备份"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912176.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL数据库备份</div></div></a></div><div><a href="/posts/994286255.html" title="Mysql的表无法修改、删除等操作，卡死、锁死情况的处理办法"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672925.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">Mysql的表无法修改、删除等操作，卡死、锁死情况的处理办法</div></div></a></div><div><a href="/posts/75c6e52f.html" title="MySQL基本使用"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1515952743786.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">MySQL基本使用</div></div></a></div><div><a href="/posts/2844609012.html" title="第零-MySQL写在前面"><img class="cover" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912181.webp" alt="cover"><div class="content is-center"><div class="date"><i class="fas fa-history fa-fw"></i> 2024-04-26</div><div class="title">第零-MySQL写在前面</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><svg class="meta_icon" style="width:22px;height:22px;position:relative;top:5px"><use xlink:href="#icon-mulu1"></use></svg><span style="font-weight:bold">目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC16%E7%AB%A0-%E5%8F%98%E9%87%8F%E3%80%81%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E4%B8%8E%E6%B8%B8%E6%A0%87"><span class="toc-text">第16章_变量、流程控制与游标</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%8F%98%E9%87%8F"><span class="toc-text">1. 变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E7%B3%BB%E7%BB%9F%E5%8F%98%E9%87%8F"><span class="toc-text">1.1 系统变量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-1-%E7%B3%BB%E7%BB%9F%E5%8F%98%E9%87%8F%E5%88%86%E7%B1%BB"><span class="toc-text">1.1.1 系统变量分类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-2-%E6%9F%A5%E7%9C%8B%E7%B3%BB%E7%BB%9F%E5%8F%98%E9%87%8F"><span class="toc-text">1.1.2 查看系统变量</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E7%94%A8%E6%88%B7%E5%8F%98%E9%87%8F"><span class="toc-text">1.2 用户变量</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-1-%E7%94%A8%E6%88%B7%E5%8F%98%E9%87%8F%E5%88%86%E7%B1%BB"><span class="toc-text">1.2.1 用户变量分类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-2-%E4%BC%9A%E8%AF%9D%E7%94%A8%E6%88%B7%E5%8F%98%E9%87%8F"><span class="toc-text">1.2.2 会话用户变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-3-%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-text">1.2.3 局部变量</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-4-%E5%AF%B9%E6%AF%94%E4%BC%9A%E8%AF%9D%E7%94%A8%E6%88%B7%E5%8F%98%E9%87%8F%E4%B8%8E%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F"><span class="toc-text">1.2.4 对比会话用户变量与局部变量</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E5%AE%9A%E4%B9%89%E6%9D%A1%E4%BB%B6%E4%B8%8E%E5%A4%84%E7%90%86%E7%A8%8B%E5%BA%8F"><span class="toc-text">2. 定义条件与处理程序</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E6%A1%88%E4%BE%8B%E5%88%86%E6%9E%90"><span class="toc-text">2.1 案例分析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E5%AE%9A%E4%B9%89%E6%9D%A1%E4%BB%B6"><span class="toc-text">2.2 定义条件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E5%AE%9A%E4%B9%89%E5%A4%84%E7%90%86%E7%A8%8B%E5%BA%8F"><span class="toc-text">2.3 定义处理程序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E6%A1%88%E4%BE%8B%E8%A7%A3%E5%86%B3"><span class="toc-text">2.4 案例解决</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6"><span class="toc-text">3. 流程控制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E5%88%86%E6%94%AF%E7%BB%93%E6%9E%84%E4%B9%8B-IF"><span class="toc-text">3.1 分支结构之 IF</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E5%88%86%E6%94%AF%E7%BB%93%E6%9E%84%E4%B9%8B-CASE"><span class="toc-text">3.2 分支结构之 CASE</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84%E4%B9%8BLOOP"><span class="toc-text">3.3 循环结构之LOOP</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84%E4%B9%8BWHILE"><span class="toc-text">3.4 循环结构之WHILE</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84%E4%B9%8BREPEAT"><span class="toc-text">3.5 循环结构之REPEAT</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-6-%E8%B7%B3%E8%BD%AC%E8%AF%AD%E5%8F%A5%E4%B9%8BLEAVE%E8%AF%AD%E5%8F%A5"><span class="toc-text">3.6 跳转语句之LEAVE语句</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-7-%E8%B7%B3%E8%BD%AC%E8%AF%AD%E5%8F%A5%E4%B9%8BITERATE%E8%AF%AD%E5%8F%A5"><span class="toc-text">3.7 跳转语句之ITERATE语句</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%B8%B8%E6%A0%87"><span class="toc-text">4. 游标</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-%E4%BB%80%E4%B9%88%E6%98%AF%E6%B8%B8%E6%A0%87%EF%BC%88%E6%88%96%E5%85%89%E6%A0%87%EF%BC%89"><span class="toc-text">4.1 什么是游标（或光标）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E4%BD%BF%E7%94%A8%E6%B8%B8%E6%A0%87%E6%AD%A5%E9%AA%A4"><span class="toc-text">4.2 使用游标步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-%E4%B8%BE%E4%BE%8B"><span class="toc-text">4.3 举例</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-%E5%B0%8F%E7%BB%93"><span class="toc-text">4.5 小结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A1%A5%E5%85%85%EF%BC%9AMySQL-8-0%E7%9A%84%E6%96%B0%E7%89%B9%E6%80%A7%E2%80%94%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E7%9A%84%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-text">补充：MySQL 8.0的新特性—全局变量的持久化</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer" style="background-color: transparent;"><div id="footer-wrap"><div id="ft"><div class="ft-item-1"><div class="t-top"><div class="t-t-l"><p class="ft-t t-l-t">格言🧬</p><div class="bg-ad"><div>再看看那个光点，它就在这里，这是家园，这是我们 —— 你所爱的每一个人，你认识的一个人，你听说过的每一个人，曾经有过的每一个人，都在它上面度过他们的一生✨</div><div class="btn-xz-box"><a class="btn-xz" target="_blank" rel="noopener" href="https://stellarium.org/">点击开启星辰之旅</a></div></div></div><div class="t-t-r"><p class="ft-t t-l-t">猜你想看💡</p><ul class="ft-links"><li><a href="/posts/eec9786.html">魔改指南</a><a href="/box/nav/">网址导航</a></li><li><a href="/social/link/">我的朋友</a><a href="/comments/">留点什么</a></li><li><a href="/personal/about/">关于作者</a><a href="/archives/">文章归档</a></li><li><a href="/categories/">文章分类</a><a href="/tags/">文章标签</a></li><li><a href="/box/Gallery/">我的画廊</a><a href="/personal/bb/">我的唠叨</a></li><li><a href="/site/time/">建设进程</a><a href="/site/census/">网站统计</a></li></ul></div></div></div><div class="ft-item-2"><p class="ft-t">推荐友链⌛</p><div class="ft-img-group"><div class="img-group-item"><a href="https://www.naste.top:1024/" title="XiaoFei🥝"><img src= "" data-lazy-src="https://www.naste.top:9000/images/cat.jpg" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div><div class="img-group-item"><a href="javascript:void(0)" title="广告位招租"><img src= "" data-lazy-src="https://www.naste.top:9000/webp/65307a5828af6790.webp" alt=""/></a></div></div></div></div><div class="copyright"><span><b>&copy;2022-2024</b></span><span><b>&nbsp;&nbsp;By XiaoFei🥝</b></span></div><div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" title="博客框架为Hexo_v6.3.0"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Frame-Hexo-blue.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" title="主题版本Butterfly_v4.3.1"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Theme-Butterfly-6513df.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://vercel.com/" style="margin-inline:5px" title="本站采用多线部署，主线路托管于Vercel"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Hosted-Vercel-brightgreen.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://user.51.la/" style="margin-inline:5px" title="本站数据分析得益于51la技术支持"><img src= "" data-lazy-src="https://static.naste.top:1024/svg/blog/Analytics-51la-3db1eb.svg" alt=""/></a><a class="github-badge" target="_blank" href="https://github.com/" style="margin-inline:5px" title="本网站源码由Github提供存储仓库"><img src= "" data-lazy-src=" https://static.naste.top:1024/svg/blog/Source-Github-d021d6.svg" alt=""/></a></p></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><a class="icon-V hidden" onclick="switchNightMode()" title="浅色和深色模式转换"><svg width="25" height="25" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button class="share" type="button" title="右键模式" onclick="changeMouseMode()"><i class="fas fa-mouse"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog right_side"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button class="share" type="button" title="分享链接" onclick="share()"><i class="fas fa-share-nodes"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div class="js-pjax" id="rightMenu"><div class="rightMenu-group rightMenu-small"><a class="rightMenu-item" href="javascript:window.history.back();"><i class="fa fa-arrow-left"></i></a><a class="rightMenu-item" href="javascript:window.history.forward();"><i class="fa fa-arrow-right"></i></a><a class="rightMenu-item" href="javascript:window.location.reload();"><i class="fa fa-refresh"></i></a><a class="rightMenu-item" href="javascript:rmf.scrollToTop();"><i class="fa fa-arrow-up"></i></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-text"><a class="rightMenu-item" href="javascript:rmf.copySelect();"><i class="fa fa-copy"></i><span>复制</span></a><a class="rightMenu-item" href="javascript:window.open(&quot;https://www.baidu.com/s?wd=&quot;+window.getSelection().toString());window.location.reload();"><i class="fa fa-search"></i><span>百度搜索</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-too"><a class="rightMenu-item" href="javascript:window.open(window.getSelection().toString());window.location.reload();"><i class="fa fa-link"></i><span>转到链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-paste"><a class="rightMenu-item" href="javascript:rmf.paste()"><i class="fa fa-copy"></i><span>粘贴</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-post"><a class="rightMenu-item" href="#post-comment"><i class="fas fa-comment"></i><span>空降评论</span></a><a class="rightMenu-item" href="javascript:rmf.copyWordsLink()"><i class="fa fa-link"></i><span>复制本文地址</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-to"><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>新窗口打开</span></a><a class="rightMenu-item" id="menu-too" href="javascript:rmf.open()"><i class="fa fa-link"></i><span>转到链接</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制链接</span></a></div><div class="rightMenu-group rightMenu-line hide" id="menu-img"><a class="rightMenu-item" href="javascript:rmf.saveAs()"><i class="fa fa-download"></i><span>保存图片</span></a><a class="rightMenu-item" href="javascript:rmf.openWithNewTab()"><i class="fa fa-window-restore"></i><span>在新窗口打开</span></a><a class="rightMenu-item" href="javascript:rmf.copyLink()"><i class="fa fa-copy"></i><span>复制图片链接</span></a></div><div class="rightMenu-group rightMenu-line"><a class="rightMenu-item" href="javascript:randomPost()"><i class="fa fa-paper-plane"></i><span>随便逛逛</span></a><a class="rightMenu-item" href="javascript:switchNightMode();"><i class="fa fa-moon"></i><span>昼夜切换</span></a><a class="rightMenu-item" href="/personal/about/"><i class="fa fa-info-circle"></i><span>关于博客</span></a><a class="rightMenu-item" href="javascript:toggleWinbox();"><i class="fas fa-cog"></i><span>美化设置</span></a><a class="rightMenu-item" href="javascript:rmf.fullScreen();"><i class="fas fa-expand"></i><span>切换全屏</span></a><a class="rightMenu-item" href="javascript:window.print();"><i class="fa-solid fa-print"></i><span>打印页面</span></a></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/4.0.31/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/instant.page/5.1.0/instantpage.min.js" type="module"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdnjs.cloudflare.com/ajax/libs/pangu/4.0.7/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (true){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/js/search/local-search.js"></script><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())
setTimeout(function(){preloader.endLoading();}, 5000);
document.getElementById('loading-box').addEventListener('click',()=> {preloader.endLoading()})</script><div class="js-pjax"><script>(()=>{
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: '',
      region: '',
      onCommentLoaded: function () {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      }
    }, null))
  }

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: '',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      countELement.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const runFn = () => {
    init()
    
  }

  const loadTwikoo = () => {
    if (typeof twikoo === 'object') {
      setTimeout(runFn,0)
      return
    } 
    getScript('https://cdn.staticfile.org/twikoo/1.6.8/twikoo.all.min.js').then(runFn)
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script async src="https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script><script defer type="text/javascript" src="https://cdn1.tianli0.top/npm/sweetalert2@8.19.0/dist/sweetalert2.all.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://cdn1.tianli0.top/gh/nextapps-de/winbox/dist/winbox.bundle.min.js"></script><script async src="//at.alicdn.com/t/c/font_3586335_hsivh70x0fm.js"></script><script async src="//at.alicdn.com/t/c/font_3636804_gr02jmjr3y9.js"></script><script async src="//at.alicdn.com/t/c/font_3612150_kfv55xn3u2g.js"></script><script async src="https://cdn.wpon.cn/2022-sucai/Gold-ingot.js"></script><canvas id="universe"></canvas><canvas id="snow"></canvas><script defer src="/js/fomal.js"></script><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/aplayer/1.10.1/APlayer.min.js"></script><script src="https://cdn1.tianli0.top/npm/js-heo@1.0.12/metingjs/Meting.min.js"></script><script src="https://lib.baomitu.com/pjax/0.2.8/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show","#web_bg",".js-pjax","#bibi","body > title","#app","#tag-echarts","#posts-echart","#categories-echarts"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Java/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍡 XiaoFeiのJava学习笔记 (55)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Linux/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍼 XiaoFeiのLinux笔记 (33)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Python/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍉 XiaoFeiのPython笔记 (2)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/前端/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍟 XiaoFeiの前端笔记 (17)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item"><a class="magnet_link" href="https://www.naste.top:1024/categories/Other/"><div class="magnet_link_context" style=""><span style="font-weight:500;flex:1">🍥 XiaoFeiのOther笔记 (10)</span><span style="padding:0px 4px;border-radius: 8px;"><i class="fas fa-arrow-circle-right"></i></span></div></a></div><div class="magnet_item" style="visibility: hidden"></div><a class="magnet_link_more"  href="https://www.naste.top:1024/categories/" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(33.333333333333336% - 5px);background: #e9e9e9;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: var(--text-bg-hover)}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1675912191.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-08</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</a><div class="blog-slider__text">SpringBoot使用实现定时任务和xxl-job实现分布式任务调度</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/204253054.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://www.naste.top:9000/webp/1678672933.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2023-03-15</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">Hexo中Markdown语法与外挂标签写法汇总</a><div class="blog-slider__text">Hexo中Markdown语法与外挂标签写法汇总</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;posts/538133837.html&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '30');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 320px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/personal/about/'|| '/personal/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.naste.top/api?xiao-i-fei",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'xiao-i-fei')
    }
  </script><!-- hexo injector body_end end --></body></html>